package com.twetec.cms.adapter.pc.backend.tag;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.twetec.cms.adapter.pc.backend.tag.annotation.TplTag;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ArticleEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.*;
import com.twetec.cms.service.website.ArticleExtendService;
import com.twetec.cms.service.website.ArticleService;
import com.twetec.cms.service.website.ColumnService;
import com.twetec.cms.service.website.SiteService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service()
@Scope("prototype")
@TplTag("videoArticleList")
public class VideoArticleListTag extends GeneralVarTagBinding {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private ArticleExtendService articleExtendService;

    @Override
    public void render() {
        System.out.println("videoArticleList");


        // 接收标签参数
        Map result = Maps.newHashMap();
        // 栏目id
        Long columnId = (this.getAttributeValue("columnId") instanceof String) ?
                Long.parseLong((String) this.getAttributeValue("columnId")) : (Long) this.getAttributeValue("columnId");
        // 页码
        Integer page = (this.getAttributeValue("page") instanceof String) ?
                Integer.parseInt((String) this.getAttributeValue("page")) : (Integer) this.getAttributeValue("page");
        // 页面容量
        Integer limit = (this.getAttributeValue("limit") instanceof String) ?
                Integer.parseInt((String) this.getAttributeValue("limit")) : (Integer) this.getAttributeValue("limit");
        // 文章类型
        String type = (String) this.getAttributeValue("type");

        QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
        articlePOQueryWrapper.eq("COLUMN_ID", columnId);
        // 对比ArticleListTag添加了属性判断,和文章类型判断。
        articlePOQueryWrapper.eq("ATTRIBUTE", ArticleEnum.ATTRIBUTE_VIDEO);
        articlePOQueryWrapper.eq("TYPE", type);
        articlePOQueryWrapper.eq("IS_RECOVERY", 0);
        articlePOQueryWrapper.orderByDesc("SORT");
        articlePOQueryWrapper.orderByAsc("ID");
        Page<ArticlePO> articlePOPage = articleService.page(new Page<>(page, limit), articlePOQueryWrapper);
        List<ArticlePO> records = articlePOPage.getRecords();

        if (ValidateUtil.isNullOrEmpty(records)) {
            // 查询文章对应的站点的信息
            SitePO sitePO = siteService.getById(records.get(0).getSiteId());

            // 拼上站点的域名
            String articleUrl =  sitePO.getDomainUrl();
            ColumnPO columnPO = columnService.getById(columnId);
            // 如果不是顶级栏目，就通过xPath获取祖先级栏目的id
            if (!columnPO.getParentId().equals(0L)) {
                String[] columnSplit = columnPO.getXpath().split("-");
                // 遍历祖先级栏目的id集合，并获取栏目的编码
                for (int j = 1; j < columnSplit.length; j++) {
                    ColumnPO columnParentPO = columnService.getById(columnSplit[j]);
                    // 判断是否查询到，查到就拼接
                    if (!ValidateUtil.isNullOrEmpty(columnParentPO)) {
                        articleUrl = articleUrl + "/" + columnParentPO.getEncoded();
                    }
                }
            }

            // 拼上所属栏目的encoded
            articleUrl = articleUrl + "/" + columnPO.getEncoded();

            if (!ValidateUtil.isNullOrEmpty(records)) {
                for (ArticlePO articlePO : records) {

                    // 文章标题
                    String title = articlePO.getTitle();
                    // 发布时间 Date
                    String releaseTime = DateUtil.formatDateTime(articlePO.getReleaseTime());
                    // 对应url
                    //String url = "1231.com";
                    // 属性，返回中文
//					 String attribute = ArticleEnum.getArticleEnumMap().get(articlePO.getAttribute());
                    String attribute = articlePO.getAttribute();
                    // 公告开始时间
                    String gmtAnnouncementStart = DateUtil.formatDateTime(articlePO.getGmtAnnouncementStart());
                    // 公告结束时间
                    String gmtAnnouncementEnd = DateUtil.formatDateTime(articlePO.getGmtAnnouncementEnd());
                    // 封面类型
                    String coverType = articlePO.getCoverType();
                    // 来源
                    String origin = articlePO.getOrigin();
                    // 作者
                    String author = articlePO.getAuthor();
                    // 封面
                    List<Map<String, String>> coverListJson = new ArrayList<Map<String, String>>();

                    // 当封面的json字符串不为空时才进行转换
                    if (StringUtils.isNotEmpty(articlePO.getCover())) {
                        // 将json字符数组转化为对象
                        List<UrlConvert> urlConvertList = JSONArray.parseArray(articlePO.getCover(), UrlConvert.class);
                        // 遍历，添加到map中
                        for (UrlConvert urlConvert : urlConvertList) {
                            HashMap<String, String> coverMap = new HashMap<>();
                            coverMap.put("url", urlConvert.getFileUrl());
                            coverListJson.add(coverMap);
                        }
                    }

                    // 如果文章类型是图文和公告
                    String url = "";
                    if (ArticleEnum.TYPE_GONG_GAO_ZI_XUN.getValue().equals(articlePO.getType()) ||
                            ArticleEnum.TYPE_TU_WEN_ZI_XUN.getValue().equals(articlePO.getType())) {
                        url = articleUrl + "/" + DateUtil.format(articlePO.getReleaseTime(), "yyyyMMdd") + "/" + articlePO.getId() + ".html";
                        result.put("url", url);
                    } else {
                        // 如果文章类型是下载文件和跳转链接,就从扩展表的content字段
                        QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
                        articleExtendPOQueryWrapper.eq("ARTICLE_ID", articlePO.getId());
                        ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);
                        result.put("url", articleExtendPO.getContent());
                    }
                    // 文章类型
                    String articleType = articlePO.getType();
                    // 发布途径
                    String releaseChannel = articlePO.getReleaseChannel();

                    // 返回标签参数
                    result.put("title", title);
                    result.put("releaseTime", releaseTime);
                    result.put("gmtAnnouncementStart", gmtAnnouncementStart);
                    result.put("gmtAnnouncementEnd", gmtAnnouncementEnd);
                    result.put("coverType", coverType);
                    result.put("origin", origin);
                    result.put("author", author);
                    result.put("coverListJson", coverListJson);
                    // 只有封面的接送字符串不为空时，才取出第一个
                    if (!ValidateUtil.isNullOrEmpty(coverListJson)) {
                        result.put("cover", coverListJson.get(0).get("url"));
                    }
                    result.put("type", articleType);
                    result.put("releaseChannel", releaseChannel);

                    this.binds(result);
                    this.doBodyRender();
                }
            }
        }

    }
	/**
	 * 标签文档
	 *
	 * @return
	 */
	public static TagDocObject doc() {
		TagDocObject tagDocObject = new TagDocObject();
		tagDocObject.setTagName("videoArticleList");
		tagDocObject.setDesc("图片文章列表标签");
		tagDocObject.setExample("<#videoArticleList columnId=\"123\" page=\"1\" limit=\"7\" type=\"PC\" var=\"data\">\n" +
				"                <img src=${data.coverListJson!} alt=\"\">\n" +
				"                    <p>${data.title}</p>\n" +
				"                </#videoArticleList>");

		tagDocObject.setParamDesc("columnId：所属栏目id\n" +
				"page：页码\n" +
				"limit：页条目数\n" +
				"type：文章类型(图文咨询TU_WEN_ZI_XUN,下载文件XIA_ZAI_WEN_JIAN,跳转链接TIAO_ZHUAN_LIAN_JIE,公告咨询GONG_GAO_ZI_XUN)\n" +
				"--------- var: 标签的数据结果集 ---------\n" +
				"title：文章标题\n" +
				"releaseTime：发布时间\n" +
				"url：对应url\n" +
				"releaseChannel：发布渠道(PC,H5,API)\n" +
				"cover：封面图\n" +
				"origin：来源\n" +
				"author：作者\n" +
				"type：文章类型(图文咨询TU_WEN_ZI_XUN,下载文件XIA_ZAI_WEN_JIAN,跳转链接TIAO_ZHUAN_LIAN_JIE,公告咨询GONG_GAO_ZI_XUN)");

		tagDocObject.setOtherDesc("无");

		return tagDocObject;
	}


}
